package com.zfei.gfb.util;

import com.zfei.gfb.core.HttpConf;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author fgh
 */
public class Httpc {
    private static Logger logger = LoggerFactory.getLogger(Httpc.class);

    private static class Holder {
        static final Httpc INSTANCE = create();
    }

    private HttpConf conf;

    private CloseableHttpClient client;

    public Httpc(HttpConf conf) {
        if (conf == null) {
            throw new IllegalArgumentException();
        }

        HttpClientBuilder builder = HttpClients.custom();
        if (conf.getConnectionConfig() != null) {
            builder.setDefaultConnectionConfig(conf.getConnectionConfig());
        }
        if (conf.getRequestConfig() != null) {
            builder.setDefaultRequestConfig(conf.getRequestConfig());
        }
        if (conf.getMaxConnTotal() > 0) {
            builder.setMaxConnTotal(conf.getMaxConnTotal());
        }
        if (conf.getMaxConnPerRoute() > 0) {
            builder.setMaxConnPerRoute(conf.getMaxConnPerRoute());
        }

        this.conf = conf;
        this.client = builder.build();
    }

    public static Httpc create() {
        return new Httpc(HttpConf.create());
    }

    public static Httpc getInstance() {
        return Holder.INSTANCE;
    }

    public String execute(HttpUriRequest request) throws IOException {
        try (CloseableHttpResponse response = client.execute(request)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }

            EntityUtils.consumeQuietly(response.getEntity());
            logger.error("http execute failed, uri={}, statusCode={}", request.getURI(), statusCode);
            return null;
        }
    }

    public String execute(HttpUriRequest request, Integer timeout) throws IOException {
        if (timeout != null && timeout > 0) {
            return execute(RequestBuilder.copy(request).setConfig(RequestConfig.copy(this.conf.getRequestConfig())
                    .setSocketTimeout(timeout).build()).build());
        } else {
            return execute(request);
        }
    }

    public String post(String url, Map<String, Object> params) {
        return post(url, params, null, null);
    }

    public String post(String url, Map<String, Object> params, Map<String, String> headers) {
        return post(url, params, headers, null);
    }

    public String post(String url, Map<String, Object> params, Map<String, String> headers, Integer timeout) {
        try {
            RequestBuilder rb = RequestBuilder.post(url).setCharset(StandardCharsets.UTF_8);
            if (params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    rb.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
                }
            }
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    rb.addHeader(entry.getKey(), entry.getValue());
                }
            }

            HttpUriRequest request = rb.build();
            String response = execute(request, timeout);
            logger.info("http request: url={}, params={}, res={}", request.getURI(), Gsons.toJson(params), response);
            return response;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return null;
    }

    public String post(String url, String body) {
        return post(url, body, null, null);
    }

    public String post(String url, String body, Map<String, String> headers) {
        return post(url, body, headers, null);
    }

    public String post(String url, String body, Map<String, String> headers, Integer timeout) {
        try {
            RequestBuilder rb = RequestBuilder.post(url).setCharset(StandardCharsets.UTF_8);
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    rb.addHeader(entry.getKey(), entry.getValue());
                }
            }
            HttpEntity entity = EntityBuilder.create().setText(body).setContentType(ContentType.APPLICATION_JSON).build();
            HttpUriRequest request = rb.setEntity(entity).build();
            String response = execute(request, timeout);
            logger.info("http request: url={}, body={},res={}", request.getURI(), body, response);
            return response;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return null;
    }
}
